package com.gxa.hualian.controller;

import com.gxa.hualian.pojo.User;
import com.gxa.hualian.service.UserService;
import com.gxa.hualian.util.JsonResult;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @Author 杨天可
 * @Date 2020/10/21 11:22
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    //会员注册
    @RequestMapping("/reg")
    public Map reg(@RequestParam("name") String name, @RequestParam("phone")
            String phone, @RequestParam("captcha") String captcha) {
        User user = new User();
        //判断验证码是否合法
        //从redis中获取验证码
        BoundValueOperations<String, Object> op = redisTemplate.boundValueOps(phone);
        Object o = op.get();

        JsonResult jsonResult = new JsonResult();
        if (captcha.equals(o)) {
            //如果合法，将个人信息+注册时间添加到数据库
            user.setRegDate(new Date());
            user.setName(name);
            user.setPhone(phone);
            userService.insert(user);
            jsonResult.setCode("200");
            jsonResult.setMsg("注册成功");
        } else {
            //如果不合法，返回注册失败，验证码错误
            jsonResult.setCode("400");
            jsonResult.setMsg("验证码不合法");
        }
        return jsonResult.getValues();
    }

    //会员登录
    @PostMapping("/login")
    public Map login(@RequestParam("phone") String phone) {
        return userService.login(phone);
    }

    //我的优惠券
    @PostMapping("/getTktList")
    public Map getTktList(String phone){
      return  userService.getTktList(phone);
    }
}

